package com.todo.content.application.frontend.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.todo.common.common.entity.response.BizPageResponse;
import com.todo.common.common.entity.response.BizResponse;
import com.todo.common.common.entity.response.page.PageResult;
import com.todo.common.common.enums.BizErrorCodeEnum;
import com.todo.common.common.exception.BizException;
import com.todo.content.application.convert.ContentConvert;
import com.todo.content.application.entity.bo.ContentDetailBO;
import com.todo.content.application.entity.bo.ContentInfoBO;
import com.todo.content.application.entity.condition.ContentInfoConditionBO;
import com.todo.content.application.frontend.service.ContentInfoAggService;
import com.todo.content.application.remote.UserInfoRemoteService;
import com.todo.content.application.service.ContentInfoService;
import com.todo.content.iface.frontend.request.*;
import com.todo.content.iface.frontend.response.ContentBaseVO;
import com.todo.content.iface.frontend.response.ContentDetailVO;
import com.todo.user.api.response.BaseUserInfoResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (ContentInfo)表服务实现类
 *
 * @author zhangwenxiang
 * @since 2024-03-04 00:19:45
 */
@Slf4j
@Service("contentInfoAggService")
public class ContentInfoAggServiceImpl implements ContentInfoAggService {

    @Resource
    private ContentInfoService contentInfoService;
    @Resource
    private UserInfoRemoteService userInfoRemoteService;


    @Override
    public BizPageResponse<ContentBaseVO> queryContentBaseByUser(ContentBaseByUserParam param) {
        if (param == null || !param.baseCheck()) {
            return BizPageResponse.paramError("参数异常");
        }
        BizResponse<BaseUserInfoResponse> bizResponse = userInfoRemoteService.queryBaseUserAccountInfoByUserId(param.getTargetUserId());
        if (bizResponse == null || !bizResponse.isSuccess() || bizResponse.getData() == null) {
            log.error("ContentInfoAggService#queryContentBaseByUser 查询目标用户内容列表失败，目标用户不存在，userId ：【{}】", param.getTargetUserId());
            return BizPageResponse.paramError("用户不存在");
        }
        BaseUserInfoResponse userAccountResponse = bizResponse.getData();
        Boolean currentLoginUser = userAccountResponse.getUserId().equals(param.get_user().getUserId());

        ContentInfoConditionBO request = new ContentInfoConditionBO();
        request.setUserId(param.getTargetUserId());
        request.setPageIndex(param.getPageIndex());
        request.setPageSize(param.getPageSize());
        request.setPageIndex(param.getPageIndex());
        PageResult<ContentInfoBO> pageResult = contentInfoService.queryContentInfoByCondition(request);
        PageResult<ContentBaseVO> result = ContentConvert.buildPageContentBaseVO(pageResult, userAccountResponse, currentLoginUser);
        return BizPageResponse.success(result);
    }

    @Override
    public BizResponse<ContentDetailVO> queryContentDetailById(ContentDetailByIdParam param) {
        if (param == null || !param.baseCheck()) {
            return BizResponse.paramError("参数异常");
        }
        ContentDetailBO contentDetailBO = contentInfoService.queryContentDetailById(Long.valueOf(param.getContentId()));
        if (contentDetailBO == null) {
            log.warn("ContentInfoAggService#queryContentDetailById 根据主键查询内容详情信息完成，数据为空 contentId：【{}】", param.getContentId());
            return BizResponse.success();
        }
        BizResponse<BaseUserInfoResponse> bizResponse = userInfoRemoteService.queryBaseUserAccountInfoByUserId(contentDetailBO.getContentInfoBO().getUserId());
        if (bizResponse == null || !bizResponse.isSuccess() || bizResponse.getData() == null){
            log.error("ContentInfoAggService#queryContentDetailById 根据主键查询内容详情信息完成，目标用户不存在，userId ：【{}】", contentDetailBO.getContentInfoBO().getUserId());
            return BizResponse.operationFailed("用户操作异常，请刷新后操作");
        }
        ContentDetailVO contentDetailVO = ContentConvert.convertToContentDetailVO(contentDetailBO,bizResponse.getData());
        if (param.get_user().getUserId().equals(contentDetailBO.getContentInfoBO().getUserId())) {
            contentDetailVO.setBelongCurrentUser(true);
        } else {
            contentDetailVO.setBelongCurrentUser(false);
        }
        return BizResponse.success(contentDetailVO);
    }

    @Override
    public BizResponse<Boolean> insertContent(InsertContentParam param) {
        if (param == null || !param.baseCheck()) {
            return BizResponse.paramError("参数异常");
        }
        ContentDetailBO contentDetailBO = ContentConvert.convertToInsertContentParam(param);
        Long contentId = contentInfoService.insertContentDetail(contentDetailBO);
        log.info("ContentInfoAggService#insertContent 插入内容完成，param：【{}】,contentId：【{}】", JSONObject.toJSONString(param), contentId);
        if (contentId == null) {
            return BizResponse.success(false);
        }
        return BizResponse.success(true);
    }

    @Override
    public BizResponse<Boolean> updateContent(UpdateContentParam param) {
        if (param == null || !param.baseCheck()) {
            return BizResponse.paramError("参数异常");
        }
        ContentDetailBO contentDetailBO = contentInfoService.queryContentDetailById(Long.valueOf(param.getContentId()));
        if (contentDetailBO == null) {
            log.warn("ContentInfoAggService#updateContent 根据主键查询内容详情信息完成，数据为空 contentId：【{}】", param.getContentId());
            return BizResponse.operationFailed("当前内容不存在，请刷新后操作");
        }
        if (!contentDetailBO.getContentInfoBO().getUserId().equals(param.get_user().getUserId())) {
            log.warn("ContentInfoAggService#updateContent 根据主键查询内容详情信息完成，用户信息异常，不属于作者，无法操作 param：【{}】,contentDetailBO：【{}】", JSONObject.toJSONString(param), JSONObject.toJSONString(contentDetailBO));
            return BizResponse.operationFailed("当前内容不属于您，无法操作");
        }
        ContentDetailBO updateContentDetail = ContentConvert.convertToContentDetailBO(param);
        Boolean updateResult = contentInfoService.updateContentDetail(updateContentDetail);
        return BizResponse.success(updateResult);
    }

    @Override
    public BizResponse<Boolean> removeContentById(RemoveContentByIdParam param) {
        if (param == null || !param.baseCheck()) {
            return BizResponse.paramError("参数异常");
        }
        List<Long> contentIdList = param.getContentIdList().stream().map(Long::valueOf).collect(Collectors.toList());
        List<ContentInfoBO> contentInfoBOList = contentInfoService.queryContentInfoByIdList(contentIdList);
        if (CollectionUtils.isEmpty(contentInfoBOList)) {
            return BizResponse.success();
        }
        List<Long> removeContentIdList = new ArrayList<>();
        for (ContentInfoBO contentInfoBO : contentInfoBOList) {
            if (!contentInfoBO.getUserId().equals(param.get_user().getUserId())) {
                throw new BizException(BizErrorCodeEnum.ILLEGAL_OPERATION, "当前内容不属于您，无法操作");
            }
            removeContentIdList.add(contentInfoBO.getId());
        }

        Boolean removeResult = contentInfoService.removeContentByIdList(removeContentIdList);
        return BizResponse.success(removeResult);
    }

}
